package com.guqj.pattern.observer;

import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {

	private List<Observer> observers = null;

	private float temperature; // 温度
	private float humidity; // 湿度
	private float pressure; // 气压

	public WeatherData() {
		observers = new ArrayList<>();
	}

	@Override
	public void registerObserver(Observer o) {
		if (!observers.contains(o)) {
			observers.add(o);
		}
	}

	@Override
	public void removeObserver(Observer o) {
		int i = observers.indexOf(o);
		observers.remove(i);
	}

	@Override
	public void notifyObserver() {
		if (observers == null || observers.size() == 0) {
			return;
		}
		for (int i = 0, j = observers.size(); i < j; i++) {
			Observer observer = observers.get(i);
			observer.update(temperature, humidity, pressure);
		}
	}

	public void setMeasurements(float temperature, float humidity, float pressure) {
		this.temperature = temperature;
		this.humidity = humidity;
		this.pressure = pressure;
		measurementsChanged();
	}
	
	public void measurementsChanged() {
		notifyObserver();
	}
}
